package com.yanqu.road.server.gameplayer.module.activity.suitang;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.suitang.config.SuiTangConfigSync;
import com.yanqu.road.entity.activity.suitang.data.SuiTangUserData;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.task.args.activity.TongBingRedPacketValueArgs;
import com.yanqu.road.logic.bussiness.activity.SuiTangActivityBusiness;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.pb.activity.suitang.SuiTang;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.suitang.SuiTangMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.pb.SuiTangPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;

import java.util.concurrent.ConcurrentHashMap;

public class SuiTangModule extends GeneralModule {
    public SuiTangModule(GamePlayer player) {
        super(player);
    }

    private SuiTangUserData userData;

    @Override
    public boolean loadData() {
        if (inShowTime()) {
            SuiTangConfigSync config = SuiTangMgr.getConfig();
            userData = SuiTangActivityBusiness.getSuiTangUserData(config.getActivityId(), getUserId());
            if (userData == null) {
                initUserData();
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                SuiTangActivityBusiness.addSuiTangUserData(userData);
            } else if (userData.isUpdateOption()) {
                SuiTangActivityBusiness.updateSuiTangUserData(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        suiTangLogin();
    }

    /**
     * 刷新活动 || 登录
     */
    public void suiTangLogin() {
        initUserData();
        crossLogin();
        syncConfig();
        syncUserData();

        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config != null) {
            int muBingLingItem = config.getParamConfig().getMuBingLingItem();
            syncRemainMuBingNum(muBingLingItem);
        }
    }

    /**
     * 初始化玩家数据
     */
    private synchronized void initUserData() {
        if (inShowTime()) {
            SuiTangConfigSync config = SuiTangMgr.getConfig();
            if (userData == null || config.getActivityInfo().getActivityId() != userData.getActivityId()) {
                SuiTangUserData tempUserData = new SuiTangUserData();
                tempUserData.setActivityId(config.getActivityId());
                tempUserData.setUserId(getUserId());
                tempUserData.setPositionId(0);
                tempUserData.setZhanGong(0);
                tempUserData.setWorshipTime(0);
                tempUserData.setWorshipEndPeriodTime(0);
                tempUserData.setSkinExchangeMap(new ConcurrentHashMap<>());
                tempUserData.setInsertOption();
                tempUserData.setUnionId(player.getUserInfo().getUnionUid());
                userData = tempUserData;
            }
        }
    }

    /*
     * inShowTime
     */
    private boolean inShowTime() {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return false;
        }
        return true;
    }

    /**
     * 登录时上传数据到跨服
     */
    public void crossLogin() {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            int activityId = config.getActivityInfo().getActivityId();

            if (checkNoGroupSyncBaseDataMsg(config)) {
                return;
            }

            SuiTang.CrossSuiTangLoginReqMsg.Builder builder = SuiTang.CrossSuiTangLoginReqMsg.newBuilder();
            builder.setActivityId(activityId);
            builder.setUserId(player.getUserId());
            builder.setServerId(GameServer.getInstance().getServerId());
            builder.setUnionUid(player.getUserInfo().getUnionUid());
            builder.setTotalAbility(player.getModule(PatronsModule.class).getSuiTangPatronsNAbility(config.getParamConfig().getSuiTangPlayerEveryJobPatronsNumMax()));
            builder.setSoldierAddition(player.getModule(PatronsModule.class).getSuiTangSoldierAddition());
            builder.setPatronsNSum(player.getModule(PatronsModule.class).getSuiTangPatronsNSum(config.getParamConfig().getSuiTangPlayerEveryJobPatronsNumMax()));
            builder.setPatronsTotalNum(player.getModule(PatronsModule.class).getUserPatronsList().size());
            builder.setUserBaseInfo(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
            player.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_SUI_TANG_LOGIN, builder, activityId);
        }
    }

    public SuiTang.CrossSuiTangTeamParam.Builder getTeamParam() {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            if (checkNoGroupSyncBaseDataMsg(config)) {
                return null;
            }

            SuiTang.CrossSuiTangTeamParam.Builder builder = SuiTang.CrossSuiTangTeamParam.newBuilder();
            builder.setTotalAbility(player.getModule(PatronsModule.class).getSuiTangPatronsNAbility(config.getParamConfig().getSuiTangPlayerEveryJobPatronsNumMax()));
            builder.setSoldierAddition(player.getModule(PatronsModule.class).getSuiTangSoldierAddition());
            builder.setPatronsNSum(player.getModule(PatronsModule.class).getSuiTangPatronsNSum(config.getParamConfig().getSuiTangPlayerEveryJobPatronsNumMax()));
            builder.setPatronsTotalNum(player.getModule(PatronsModule.class).getUserPatronsList().size());
            return builder;
        }
        return null;
    }

    /**
     * @return false需要再上跨服取数据
     */
    private boolean checkNoGroupSyncBaseDataMsg(SuiTangConfigSync config) {
        ActivityInfo activityInfo = config.getActivityInfo();

        // 新版活动，还没锁名单，给个假数据
        boolean hadGroup = GameUnionActivityGroupMgr.getGroupMap(config.getActivityInfo().getActivityId()) != null;
        if (!hadGroup) {
            SuiTang.SuiTangSyncBaseDataRespMsg.Builder builder = SuiTang.SuiTangSyncBaseDataRespMsg.newBuilder();
            builder.setJoinStatus(2);
            builder.setSyncPatronsTime(0);
            player.sendPacket(ClientProtocol.U_SUI_TANG_SYNC_BASE_DATA, builder);
            return true;
        }

        // 新版活动，锁完名单有资格，上跨服取
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), player.getUserId());
        if (groupId != UnionActivityGroupHelper.NO_GROUP_ID) {
            return false; // 有资格可以走远逻辑
        }

        // 新版活动，锁完名单没资格，给个假数据
        SuiTang.SuiTangSyncBaseDataRespMsg.Builder builder = SuiTang.SuiTangSyncBaseDataRespMsg.newBuilder();
        builder.setJoinStatus(0); // 商会无资格
        builder.setSyncPatronsTime(0);
        player.sendPacket(ClientProtocol.U_SUI_TANG_SYNC_BASE_DATA, builder);
        return true;
    }

    /**
     * 同步配置
     */
    public void syncConfig() {
        SuiTangConfigSync configSync = SuiTangMgr.getConfig();
        if (configSync != null && ActivityMgr.activityInShowTime(configSync.getActivityInfo())) {
            SuiTang.SuiTangConfigSync.Builder builder = SuiTangPb.parseSuiTangSyncConfigRespMsg(configSync, player.getUserInfo().getLanguage());
            player.sendPacket(ClientProtocol.U_SUI_TANG_SYNC_CONFIG, builder);
        }
    }

    /*
     * 同步用户数据
     */
    public void syncUserData() {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config != null && inShowTime()) {
            SuiTang.SuiTangUserDataSyncMsg.Builder resp = SuiTang.SuiTangUserDataSyncMsg.newBuilder();
            resp.setActivityId(userData.getActivityId());
            resp.setWorshipTime(userData.getWorshipTime());
            resp.setWorshipTimeEndPeriod(userData.getWorshipEndPeriodTime());
            resp.setPositionId(userData.getPositionId());
            resp.setZhanGong(userData.getZhanGong());
            resp.setUnionId(userData.getUnionId());
            resp.setWinnerId(0L);

//            int groupId = GameUnionActivityGroupMgr.getGroupId(config.getActivityInfo().getActivityId(), getUserId());
//            if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
//                // 没资格不发跨服
//                player.sendPacket(ClientProtocol.U_SUI_TANG_USER_DATA_SYNC, resp);
//            } else {
//                // 有资格才上跨服
//                player.sendUnionActivityGroupPacket(CrossProtocol.C2_SUI_TANG_SYNC_USER_DATA, resp, config.getActivityInfo().getActivityId());
//            }
            player.sendPacket(ClientProtocol.U_SUI_TANG_USER_DATA_SYNC, resp);
        }
    }

    /**
     * 膜拜
     */
    public void worship() {
        SuiTang.SuiTangCityWinnerWorshipRespMsg.Builder respMsg = SuiTang.SuiTangCityWinnerWorshipRespMsg.newBuilder();
        respMsg.setRet(0);
        if (!inShowTime()) {
            respMsg.setRet(GameErrorCode.E_SUI_TANG_NO_OPERATE_TIME);
            player.sendPacket(ClientProtocol.U_SUI_TANG_CITY_WINNER_WORSHIP, respMsg);
            return;
        }

        long zeroTime = DateHelper.getTodayZeroTimeStamp();
        if (userData.getWorshipTime() >= zeroTime) {
            respMsg.setRet(GameErrorCode.E_SUI_TANG_WORSHIP_DO);
            player.sendPacket(ClientProtocol.U_SUI_TANG_CITY_WINNER_WORSHIP, respMsg);
            return;
        }
        userData.setWorshipTime(System.currentTimeMillis());

        String reward = SuiTangMgr.getWorshipReward(false);
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.SuiTang, eLogMoneyType.SuiTangWorshipReward);

        respMsg.setReward(reward);
        player.sendPacket(ClientProtocol.U_SUI_TANG_CITY_WINNER_WORSHIP, respMsg);
        syncUserData();
    }

    /**
     * 膜拜-巅峰
     */
    public void worshipEndPeriod() {
        SuiTang.SuiTangCityWinnerWorshipRespMsg.Builder respMsg = SuiTang.SuiTangCityWinnerWorshipRespMsg.newBuilder();
        respMsg.setRet(0);
        if (!inShowTime() || SuiTangMgr.getConfig() == null || SuiTangMgr.getConfig().getActivityInfo().getChildType() != 2) {
            respMsg.setRet(GameErrorCode.E_SUI_TANG_NO_OPERATE_TIME);
            player.sendPacket(ClientProtocol.U_SUI_TANG_CITY_WINNER_WORSHIP, respMsg);
            return;
        }

        long zeroTime = DateHelper.getTodayZeroTimeStamp();
        if (userData.getWorshipEndPeriodTime() >= zeroTime) {
            respMsg.setRet(GameErrorCode.E_SUI_TANG_WORSHIP_DO);
            player.sendPacket(ClientProtocol.U_SUI_TANG_CITY_WINNER_WORSHIP, respMsg);
            return;
        }
        userData.setWorshipEndPeriodTime(System.currentTimeMillis());

        String reward = SuiTangMgr.getWorshipReward(true);
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.SuiTang, eLogMoneyType.SuiTangWorshipReward);

        respMsg.setReward(reward);
        player.sendPacket(ClientProtocol.U_SUI_TANG_CITY_WINNER_WORSHIP, respMsg);
        syncUserData();
    }

    /**
     * 更新用户数据
     */
    public void updateUserData(SuiTang.CrossSuiTangSyncUserDataMsg reqMsg) {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config == null) {
            return;
        }
        if (!ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        if (userData == null) {
            return;
        }
        // 其他需要同步到游戏服的数据在这处理
        userData.setUnionId(reqMsg.getUnionId());
        userData.setZhanGong(reqMsg.getZhanGong());
        userData.setPositionId(reqMsg.getPositionId());
        if (reqMsg.hasSpeedUpNum()) {
            userData.setMoveSpeedUpNum(reqMsg.getSpeedUpNum());
        }
        // 同步玩家数据
        syncUserData();
    }

    /**
     * 能否购买礼包
     */
    public boolean canBuyRechargeGift(int mallId) {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            return false;
        }

        long stage1BeginTime = config.getStage1TimeList().get(0).get(0);
        long zeroTimeStamp = DateHelper.getZeroTimeStamp(stage1BeginTime) + 10 * DateHelper.MINUTE_MILLIONS;
        long now = System.currentTimeMillis();
        if (now < zeroTimeStamp) {
            return false;
        }
        if (!hasCamp()) {
            return false;
        }

        return true;
    }

    /**
     * 是否有阵营
     */
    public boolean hasCamp() {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return false;
        }
        return !userData.getUnionId().isEmpty() && GameUnionActivityGroupMgr.getGroupId(config.getActivityInfo().getActivityId(), getUserId()) != UnionActivityGroupHelper.NO_GROUP_ID;
    }

    /*
     * 增加募兵令
     */
    public void useMuBingNum(GoodsInfo goodsInfo, long count) {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config == null || (!ActivityMgr.activityInTime(config.getActivityInfo()) && !config.inReadyTime())) {
            log.error("sui tang activity no in time , userId {} , use mu bing ling num {}.", player.getUserId(), count);
            return;
        }

        SuiTang.CrossMuBingLingAddReqMsg.Builder builder = SuiTang.CrossMuBingLingAddReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setCount(count);
        builder.setGoodId(goodsInfo.getGoodsId());
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_SUI_TANG_USE_MU_BING_LING, builder, config.getActivityInfo().getActivityId());

        syncRemainMuBingNum(goodsInfo.getGoodsId());
    }

    /**
     * 跨服加阵营红包
     */
    public void addCrossRedPacket(GoodsInfo goodsInfo, long num) {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            log.error("sui tang activity no in time , userId {} , use red packet num {}.", player.getUserId(), num);
            return;
        }

        SuiTang.CrossSuiTangRedPacketAddReqMsg.Builder builder = SuiTang.CrossSuiTangRedPacketAddReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setNum((int) num);
        builder.setGoodId(goodsInfo.getGoodsId());
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_SUI_TANG_RED_PACKET_ADD, builder, config.getActivityInfo().getActivityId());
    }

    /**
     * 跨服加民心
     */
    public void addMinXin(long num) {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            log.error("sui tang activity no in time , userId {} , use min xin num {}.", player.getUserId(), num);
            return;
        }

        SuiTang.CrossSuiTangAddMinXinReqMsg.Builder builder = SuiTang.CrossSuiTangAddMinXinReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setNum((int) num);
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_SUI_TANG_MIN_XIN_ADD, builder, config.getActivityInfo().getActivityId());
    }

    /**
     * 加阵营红包成就进度
     */
    public void notifyRedPackValue(int activityId, long value) {
        if (userData.getActivityId() == activityId) {
            player.notifyListenerAndSync(eGamePlayerEventType.SuiTangUnionMinXin.getValue(), new TongBingRedPacketValueArgs(activityId, value));
        }
    }

    public SuiTangUserData getUserData() {
        return userData;
    }

    public void setUserData(SuiTangUserData userData) {
        this.userData = userData;
    }

    public void syncRemainMuBingNum(int goodsId) {
        SuiTangConfigSync config = SuiTangMgr.getConfig();
        if (config == null) {
            return;
        }
        if (userData == null) {
            return;
        }
        int muBingLingItem = config.getParamConfig().getMuBingLingItem();
        if (goodsId != muBingLingItem) {
            return;
        }

        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(goodsId);
        if (goodsInfo == null) {
            return;
        }

        long itemCount = player.getModule(BagModule.class).getUserBagItemCount(muBingLingItem);

        long soldierNum = (goodsInfo.getParamList().get(0).longValue() * itemCount);

        SuiTang.CrossSuiTangSyncUserMuBingMsg.Builder synMsg = SuiTang.CrossSuiTangSyncUserMuBingMsg.newBuilder();
        synMsg.setActivityId(config.getActivityId());
        synMsg.setUserId(getUserId());
        synMsg.setRemainMuBinNum(soldierNum);

        player.sendUnionActivityGroupPacket(CrossProtocol.C2_SUI_TANG_SYNC_USER_MUBING, synMsg, synMsg.getActivityId());
    }
}
